package com.spzx.product.controller;

import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.ProductUnit;
import com.spzx.product.service.ProductUnitService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "商品单位模块")
@RestController
@RequestMapping("unit")
public class ProductUnitController extends BaseController {

    @Autowired
    ProductUnitService productUnitService;

    @Operation(summary = "条件查询商品单位分页列表")
    @RequestMapping("/list")
    public TableDataInfo list(ProductUnit productUnit) {
        startPage();
        List<ProductUnit> list = productUnitService.selectproductUnitList(productUnit);
        return getDataTable(list);
    }


    @Operation(summary = "批量删除商品单位")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        //toAjax 可以根据增删改返回的影响记录的条数，返回成功或失败AjaxResult对象
        return toAjax(productUnitService.removeBatchByIds(ids));
    }

    @Operation(summary = "新增商品单位")
    @PostMapping
    public AjaxResult add(@RequestBody ProductUnit productUnit) {
        //唯一性校验
        productUnitService.checkUnitNameUnique(productUnit);
        productUnit.setCreateBy(SecurityUtils.getUsername());
        return toAjax(productUnitService.save(productUnit));
    }

    //先查询详情
    @Operation(summary = "查询商品单位详情")
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Long id) {
        return success(productUnitService.getById(id));
    }

    //前端对详情进行展示 修改 提交更新请求
    @Operation(summary = "更新商品单位")
    @PutMapping
    public AjaxResult edit(@RequestBody ProductUnit productUnit) {
        //唯一性校验
        productUnitService.checkUnitNameUnique(productUnit);
        productUnit.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(productUnitService.updateById(productUnit));
    }

    @Operation(summary = "查询所有商品单位")
    @GetMapping("/listAll")
    public AjaxResult listAll() {
        //查询数据列表
        List<ProductUnit> productUnits = productUnitService.list();
        return success(productUnits);
    }
}
